package com.kx;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;
import com.kx.realm.CustomerRealm;

/**
 * 使用自定义realm
 */
public class TestCustomerRealmAuthenticator {
    public static void main(String[] args) {
        //1、创建securityManager
        DefaultSecurityManager securityManager = new DefaultSecurityManager();
        //2、给安全管理器设置realm
        securityManager.setRealm(new CustomerRealm());
        //3、SecurityUtils给全局安全工具类设置安全管理器
        SecurityUtils.setSecurityManager(securityManager);
        //4、关键对象subject主体
        Subject subject = SecurityUtils.getSubject();
        //5、创建令牌（身份信息，凭证信息）
        UsernamePasswordToken token = new UsernamePasswordToken("kx", "123");
        try {
            subject.login(token);
            System.out.println(subject.isAuthenticated());
        } catch (UnknownAccountException e) {
            System.out.println("用户名错误");
            e.printStackTrace();
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            System.out.println("密码错误");
        } catch (Exception e) {
            e.printStackTrace();
        }

        //认证用户进行授权
        if (subject.isAuthenticated()) {
            //1、基于角色权限控制
            System.out.println(subject.hasRole("admin"));
        }
    }
}
